package com.itheima.app.interceptor;

import com.itheima.domain.db.User;
import com.itheima.util.JwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    //进入controller之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        //获取请求路径
        String url = request.getRequestURI();

        log.info("请求路径为：{}", url);

        //1、从请求头中获取令牌
        String token = request.getHeader(jwtProperties.getAdminTokenName());
        if (token == null || token.isEmpty()) {
            throw new RuntimeException("token不允许为空");
        }

        //2、校验令牌
        try {
            log.info("jwt校验:{}", token);
            Claims claims = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            User user = new User();
            //从claims取出id和手机号
            user.setId(((Integer) claims.get("id")).longValue());
            user.setPhone((String) claims.get("phone"));
            log.info("取出来的用户id和电话为：{},{}", user.getId(), user.getPhone());
            UserHolder.set(user);
            //3、通过，放行
            return true;
        } catch (Exception ex) {
            //4、不通过
            throw new RuntimeException("token校验不通过");
        }
    }


    //页面渲染完毕之后
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.remove();
    }
}


